from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.decorators import login_required
from app.models import client,table,order,dishes,EmployeeUser,preTable,message
from django.core.paginator import Paginator
from app.views import myLog_decrator

# Create your views here.
@login_required
def waiter(request):
    return render(request,'waiter.html')


@login_required
# 信息
def info(request):
    tablelist = table.objects.all()
    tabledata = []
    for t in tablelist:
        tab = {}
        tab['id'] = t.id
        tab['state'] = t.state
        tab['number'] = t.number
        tab['cost'] = t.cost
        tabledata.append(tab)
        pass
    Tab = {'data1':tabledata}
    return render(request,'info.html',Tab)


@login_required
# 菜品
def thedishes(request):
    disheslist = dishes.objects.all()
    # 建立分页器
    paginaor = Paginator(disheslist, 3)
    # 获取当前指定页
    page = request.GET.get('page')
    disheslist = paginaor.get_page(page)
    dishesdata = []
    for d in disheslist:
        dis = {}
        dis['id'] = d.id
        dis['name'] = d.name
        dis['price'] = d.price
        dishesdata.append(dis)
        pass
    Data = {'data2':dishesdata}
    return render(request,'dishes.html',Data,{'disheslist',disheslist})


# 点餐
@login_required
def addorder(request):
    if request.POST:
        # 自动获取当前登录用户id
        operatorid = EmployeeUser.objects.get(id=request.session.get('_auth_user_id'))
        disheslist = request.POST.getlist('dishes')
        thetable = table.objects.get(id=request.POST.get("table"))
        clientid = preTable.objects.get(tableid=thetable).vipid
        for thedishes in disheslist:
            num = request.POST.get("number{0}".format(thedishes))
            for i in range(int(num)):
                order.objects.create(dishesid=dishes.objects.get(id=thedishes),clientid=clientid,operatorid=operatorid,tableid=thetable)
                # 写入日志
                myLog_decrator(request, "点餐菜品{0}顾客{1}".format(thedishes,clientid))
                pass
            pass
        return HttpResponse('OK')
    else:
        data = {
            "pretablelist":preTable.objects.all(),
            "disheslist":dishes.objects.all()
        }
        return render(request, 'order_meal.html',data)
    pass


def checkclientid(request):
    try:
        client.objects.get(id=request.POST.get("clientid"))
        data = {"resule":"可用"}
        return JsonResponse(data)
    except:
        data = {"resule": ""}
        return JsonResponse(data)
    pass


def mymessage(request):
    return render(request, 'message.html', {"messlist": message.objects.all()})
    pass